#include "detailedvideoitem.h"
#include "ui_detailedvideoitem.h"
#include<QAudioOutput>
#include<QTimer>
#include<QTime>
#include<QMouseEvent>
#include<QFileDialog>
detailedvideoitem::detailedvideoitem(QWidget*parent)
    : QWidget(parent)
    , ui(new Ui::detailedvideoitem)
{

    ui->setupUi(this);
}

detailedvideoitem::~detailedvideoitem()
{
    delete ui;
}




bool detailedvideoitem::eventFilter(QObject *watched, QEvent *event)
{
    if(watched==ui->widget_2)
    {
        if(event->type()==QEvent::MouseButtonPress)
        {
            dragPosition=QCursor::pos()-this->geometry().topLeft();
            dragPosition_pei=QCursor::pos()-apr->geometry().topLeft();
            dragPosition_sound=QCursor::pos()-ss->geometry().topLeft();
        }
        else if(event->type()==QEvent::MouseMove)
        {
            move(QCursor::pos()-dragPosition);
            apr->move(QCursor::pos()-dragPosition_pei);
            ss->move(QCursor::pos()-dragPosition_sound);
        }
    }
    if(watched==ui->pei)
    {
        if(event->type()==QEvent::Enter)
        {
            apr->show();
        }
    }
    else if(watched==apr)
    {
        if(event->type()==QEvent::Leave)
        {
            apr->close();
        }
    }
    else if(watched==ui->sound)
    {
        if(event->type()==QEvent::Enter)
        {
            ss->show();
        }
    }
    else if(watched==ss)
    {
        if(event->type()==QEvent::Leave)
        {
            ss->close();
        }
    }
}

void detailedvideoitem::init()
{
    this->setWindowFlags(Qt::FramelessWindowHint);
    ui->recommendvideolist->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->recommendvideolist->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->talklist->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->talklist->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->evaluatelist->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->evaluatelist->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->textEdit->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->textEdit->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    sc=new selectcollect;
    //增加一个视频收藏的信号
    connect(sc,&selectcollect::addonevideotocollect,this,[=](QString collectname){
        //更新ui界面
        this->storage=true;
        ov->storagenum++;
        ui->storagenum->setText(QString::number(ov->storagenum));
        ui->storage->setIcon(QPixmap(":/res/alreadystorage.png"));
        //更新视频的基本数据到数据库的videobasicinfo表中去
        db->updateinfo("videobasicinfo","id",QString::number(ov->videoid),"storagenum",QString::number(ov->storagenum));
        //更新视频的基本数据到数据库的collectinfo表中去
        db->addcollect(ov->videoid,pi->pri->name);
        //添加到收藏夹中--通过信号发送给主界面进行处理
        int videoid=ov->videoid;
        //发送信号更新个人界面中用户收藏界面
        emit addonevideotocollect(collectname,videoid);
        //将添加信息更新到数据库的用户收藏表中
        qDebug()<<"99";
        db->addonevideotocollect(pi->pri->name,collectname,videoid);
    });
    apr=new adjustrplayrate;
    apr->move(914,390);
    apr->installEventFilter(this);
    connect(apr,&adjustrplayrate::changepei,[=](float pei){
        player->setPlaybackRate(pei);
    });

    ss=new soundsum();
    ss->installEventFilter(this);
    ss->move(965,430);
    connect(ss,&soundsum::setvolumn,this,[=](int value){
        player->audioOutput()->setVolume(value/100.0);
    });
    ui->pei->installEventFilter(this);
    ui->sound->installEventFilter(this);
    ui->widget_2->installEventFilter(this);
}

void detailedvideoitem::inithistorical(historicalwatch *his,QListWidget*li)
{
    this->hisw=his;
    this->smallhislist=li;
}

void detailedvideoitem::initprivateinfo(peopleinfo *pi)
{
    this->pi=pi;
}

void detailedvideoitem::initMedia()
{
    vw=new videowidget(ui->video);
    vw->setGeometry(ui->video->x(),ui->video->y(),750,455);
    vw->show();
    player=vw->player;
    connect(player,&QMediaPlayer::playbackStateChanged,this,[=](QMediaPlayer::PlaybackState state){
        //播放器状态变化
        if(state==QMediaPlayer::PlayingState)
        {
            ui->play->setIcon(QPixmap(":/res/playicon.png"));
        }
        else{
            ui->play->setIcon(QPixmap(":/res/stopicon.png"));
        }
    });

    connect(player,&QMediaPlayer::positionChanged,this,[=](qint64 position){
        //文件播放位置变化
        int   secs=position/1000;   //秒
        int   mins=secs/60;         //分钟
        int sum=secs+mins*60;
        secs=secs % 60;             //余数秒
        QString sec;
        if(secs<10)
            sec="0"+QString::number(secs);
        else
            sec=QString::number(secs);
        QString min=QString::number(mins);
        QString positionTime=min+":"+sec;
        ui->curplay->setText(positionTime);

        qint64 postion=player->position();
        qint64 duration=player->duration();
        double lengthrate=(double)postion/duration;
        ui->line->adjustprogress(ui->line->width()*lengthrate);

    });

    connect(player,&QMediaPlayer::durationChanged,this, [=](qint64 duration){
        //文件时长变化
        int   secs=duration/1000;   //秒
        int   mins=secs/60;         //分钟
        secs=secs % 60;             //余数秒
        QString alltime=QString::asprintf("%d:%d",mins,secs);
        ui->videolength->setText(alltime);
    });
    connect(ui->line,&progressline::setprogress,this,[=](int length){
        if(player->playbackRate()==QMediaPlayer::PlayingState)
        {
            qint64 duration=player->duration();
            double rate=(double)length/750.0;
            qint64 position=duration*rate;
            player->setPosition(position);
        }

    });
}



void detailedvideoitem::initsqldatabase(databasemanage* db)
{
    this->db=db;
}

void detailedvideoitem::initvideoinfo(onevideoinfo *ovi,QVector<onevideoinfo*> recommendov)  //每次点击一个视频项后进入此界面自动填充对应视频信息
{
    ov=ovi;
    this->recommendov=recommendov;
    player->setSource(QUrl::fromLocalFile(ovi->videoaddress));
    this->setWindowIcon(QPixmap(ov->image));
    initUi();
    if(!db->judgefavor(ov->videoid,pi->pri->name))
    {
        ui->favor->setIcon(QPixmap(":/res/favoricon.png"));
        favor=false;
    }
    else
    {
        ui->favor->setIcon(QPixmap(":/res/alreadyfavoricon.png"));
        favor=true;

    }
    if(!db->judgecoin(ov->videoid,pi->pri->name)){
        ui->coin->setIcon(QPixmap(":/res/coinicon.png"));
        coin=false;
    }
    else{
        ui->coin->setIcon(QPixmap(":/res/alreadycoinicon.png"));
        coin=true;
    }
    if(!db->judegecollect(ov->videoid,pi->pri->name)){
        ui->storage->setIcon(QPixmap(":/res/storageicon.png"));
        storage=false;
    }
    else{
        ui->storage->setIcon(QPixmap(":/res/alreadystorage.png"));
        storage=true;
    }
    complementtalklist();
    complementrecommendlist();
    if(ovi->author==pi->pri->name)
    {
        ui->attention_2->setVisible(false);
        return;
    }
    if(db->isfriend(ov->author,pi->pri->name))
    {
        ui->attention_2->setText("已关注");
        ui->attention_2->setStyleSheet("background-color:#636363;color:white;border:none;");
        attention=true;
    }
    else
    {
        ui->attention_2->setText("关注");
        ui->attention_2->setStyleSheet("background-color:#00aeec;color:white;border:none;");
        attention=false;
    }
}

void detailedvideoitem::complementtalklist()
{

    if(ov==nullptr)
    {
        qDebug()<<"detailedvideoitem94:onevideoinfo is nullptr";
        return;
    }
    for(auto&e:ov->evaluates)
    {
        if(!e->istalk)
        {
            evaluateitem* evi=new evaluateitem(ui->evaluatelist);
            evi->init(e->image,e->name,e->content_type,e->content);
            int width;
            if(e->content_type=="text")
                width=400;
            else
                width=160;
            QListWidgetItem* li=new QListWidgetItem(ui->evaluatelist);
            evi->setFixedSize(QSize(width,160));
            li->setSizeHint(QSize(width,160));
        }
        else
        {
            smalltalk* sm=new smalltalk(ui->talklist);
            sm->init(e->position,e->content,e->time);
            QListWidgetItem* li=new QListWidgetItem(ui->talklist);
            li->setSizeHint(QSize(ui->talklist->width(),40));
            ui->talklist->setItemWidget(li,sm);


        }
    }
}

void detailedvideoitem::complementrecommendlist()
{
    for(auto&e:recommendov)
    {
        QListWidgetItem* li=new QListWidgetItem(ui->recommendvideolist);
        smallvideoitem* sv=new smallvideoitem(ui->recommendvideolist);
        sv->init(e->image,e->videolength,e->author,e->playnum,e->evaluatenum,e->sign,e->videoaddress,e->videoid);
        li->setSizeHint(QSize(ui->recommendvideolist->width(),100));
        ui->recommendvideolist->setItemWidget(li,sv);
    }
}

void detailedvideoitem::initUi()
{
    ui->videoname->setText(ov->sign);
    ui->playnum->setText(QString::number(ov->playnum));
   ui->talknum->setText(QString::number(ov->evaluatenum));
    ui->favornum->setText(QString::number(ov->favornum));
    ui->coinnum->setText(QString::number(ov->coinnum));
    ui->storagenum->setText(QString::number(ov->storagenum));
    ui->issuetime->setText(ov->issuetime);
    ui->videolength->setText(ov->videolength);
    ui->authorimage_2->setIcon(QPixmap(ov->authorimage));
    ui->author_2->setText(ov->author);


}

void detailedvideoitem::setmyimage(QString image)
{
    ui->myimage_evaluate->setPixmap(QPixmap(image));
    ui->myimage_evaluate->setScaledContents(true);
}

void detailedvideoitem::addtselectcollectitem(QString name, int num)
{
    selectcollectitem* si=new selectcollectitem;
    si->init(name,num);
    QListWidgetItem* li=new QListWidgetItem;
    li->setText(name);
    li->setSizeHint(QSize(241,50));
    sc->addselectitem(li,si);
}





void detailedvideoitem::on_play_clicked()
{
    // if(player->playbackRate()==QMediaPlayer::PausedState)
    // player->play();
    // else if(player->mediaStatus()==QMediaPlayer::PlayingState)
    //     player->pause();
    playstate=!playstate;
    if(playstate)
        player->play();
    else
        player->pause();
}


void detailedvideoitem::on_sound_clicked()
{
    //静音按钮
    bool mute=player->audioOutput()->isMuted();
    player->audioOutput()->setMuted(!mute);
    if(!mute)
    {
        ui->sound->setIcon(QPixmap(":/res/nosound.png"));
    }
    else
    {
        ui->sound->setIcon(QPixmap(":/res/sound.png"));
    }
}



void detailedvideoitem::on_attention_2_clicked()
{
    attention=!attention;
    QString str;
    //更新图标
    if(attention)
    {
        str="background-color:rgb(99, 99, 99);border-radius:4px;color:white;letter-spacing:6px;padding-left:5px;";
        ui->attention_2->setStyleSheet(str);
        ui->attention_2->setText("已关注");
        //存储双方的关系为好友关系到数据库中
        db->addfriendrelation(ov->author,pi->pri->name,pi->pri->image,pi->pri->udpsocket);
        db->addfriendrelation(pi->pri->name,ov->author,ov->image,ov->udpsocket);
        //将修改消息更新到聊天界面上
        frienditem* fri=new frienditem;
        fri->init(ov->author,ov->image,"",ov->udpsocket);
        emit addonefriendrelation(fri);
    }
    else
    {
        str="background-color:#00aeec;border-radius:4px;color:white;letter-spacing:6px;padding-left:5px;";
        ui->attention_2->setStyleSheet(str);
        ui->attention_2->setText("关注");
        db->removefriendrelation(pi->pri->name,ov->author);
        db->removefriendrelation(ov->author,pi->pri->name);
        emit deleteonefriendrelation(ov->author);
    }


}


void detailedvideoitem::on_favor_clicked()
{
    favor=!favor;
    int videoid=ov->videoid;
    if(favor)
    {
        //设置图标
        ui->favor->setIcon(QPixmap(":/res/alreadyfavoricon.png"));
        //更新ui及数据
        ov->favornum++;
        ui->favornum->setText(QString::number(ov->favornum));
        db->addfavor(ov->videoid,pi->pri->name);
    }
    else
    {
        ui->favor->setIcon(QPixmap(":/res/favoricon.png"));
        ov->favornum--;
        ui->favornum->setText(QString::number(ov->favornum));
        db->reducefavor(ov->videoid,pi->pri->name);
    }


    db->updateinfo("videobasicinfo","id",QString::number(videoid),"favornum",QString::number(ov->favornum));

}


void detailedvideoitem::on_coin_clicked()
{
    coin=!coin;
    int videoid=ov->videoid;
    if(coin)
    {
        ui->coin->setIcon(QPixmap(":/res/alreadycoinicon.png"));
        ov->coinnum++;
        ui->coinnum->setText(QString::number(ov->coinnum));
        db->addcoin(ov->videoid,pi->pri->name);
    }
    else
    {
        ui->coin->setIcon(QPixmap(":/res/coinicon.png"));
        ov->coinnum--;
        ui->coinnum->setText(QString::number(ov->coinnum));
        db->reducecoin(ov->videoid,pi->pri->name);
    }
    //更新到数据库中去
    db->updateinfo("videobasicinfo","id",QString::number(videoid),"coinnum",QString::number(ov->coinnum));
}




void detailedvideoitem::on_talkset_clicked()
{
    talkopen=!talkopen;
    if(talkopen)
    {
        ui->talkset->setIcon(QPixmap(":/res/talkopenicon.png"));
        ui->sendtalk->setEnabled(true);
    }
    else
    {
        ui->talkset->setIcon(QPixmap(":/res/talkcloseicon.png"));
        ui->sendtalk->setEnabled(false);
    }
}


void detailedvideoitem::on_sendtalk_clicked()
{
    if(ui->lineEdit->text().isEmpty())
        return;
    if(player->playbackRate()!=QMediaPlayer::PlayingState)
        return;
    QString str=ui->lineEdit->text();
    ui->lineEdit->clear();
    smalltalk* sm=new smalltalk(ui->talklist);
    int   secs=player->position()/1000;   //秒
    int   mins=secs/60;         //分钟
    secs=secs % 60;             //余数秒
    QString min=QString::number(mins);
    QString sec=QString::number(secs);
    if(sec.size()==1)
        sec="0"+sec;
    sec=sec.sliced(0,2);
    QString position=min+":"+sec;
    sm->init(position,str,QTime::currentTime().toString());
    QListWidgetItem* li=new QListWidgetItem(ui->talklist);
    li->setSizeHint(QSize(ui->talklist->width(),40));
    ui->talklist->setItemWidget(li,sm);

    //填充到数据库中
    db->insertvideoevaluation(ov->videoid,ov->author,QTime::currentTime().toString(),"text",str,true,position,pi->pri->image);
}


void detailedvideoitem::on_fullscreen_clicked()
{
    vw->setFullScreen();
}


void detailedvideoitem::on_pushButton_2_clicked()
{
    //更新历史观看记录
    int   secs=player->position()/1000;   //秒
    int   mins=secs/60;         //分钟
    secs=secs % 60;             //余数秒
    QString min=QString::number(mins);
    QString sec=QString::number(secs);
    if(sec.size()==1)
        sec="0"+sec;
    sec=sec.sliced(0,2);
    QString watchtime=min+":"+sec;
    ov->renewwatchposition(watchtime);
    //添加到数据库中
    db->addhistoricalwatch(pi->pri->name,watchtime,ov->videolength,ov->videoid);
    //清空该界面消息
    ui->recommendvideolist->clear();
    //更新历史记录界面和列表
    onevideoinfo* one=new onevideoinfo(hisw);
    one->duplicateone(ov);
    hisw->addhistoricalwatch(one);
    emit addsmallhistory(ov->image,ov->author,ov->issuetime,ov->sign);
    player->stop();
    this->close();

}


void detailedvideoitem::on_pei_clicked()
{

}


void detailedvideoitem::on_storage_clicked()
{
    //如果视频的作者是自己不能收藏
    if(ov->isown)
        return;
    storage=!storage;
    int videoid=ov->videoid;
    if(storage)
    {
        qDebug()<<"543";
        sc->show();
    }
    else
    {
        ui->storage->setIcon(QPixmap(":/res/storageicon.png"));
        if(ov->storagenum>0)
        {
            ov->storagenum--;
            ui->storagenum->setText(QString::number(ov->storagenum));
            //更新视频的基本数据到数据库videobasicinfo表中去
            db->updateinfo("videobasicinfo","id",QString::number(videoid),"storagenum",QString::number(ov->storagenum));
            db->reducecollect(ov->videoid,pi->pri->name);
        }
        //将视频内容从收藏夹中删除  //暂不实现
        // emit removeonevideofromcollect()
    }

}


void detailedvideoitem::on_pushButton_4_clicked()
{
    talklistopen=!talklistopen;
    if(talklistopen)
        ui->talklist->setMaximumHeight(210);
    else
        ui->talklist->setMaximumHeight(0);
}


void detailedvideoitem::on_issuebtn_clicked()
{
    QString str=ui->textEdit->toPlainText();
    ui->textEdit->clear();
    evaluateitem* ev=new evaluateitem(ui->evaluatelist);
    ev->init(pi->pri->image,pi->pri->name,"text",str);
    QListWidgetItem* li=new QListWidgetItem(ui->evaluatelist);
    li->setSizeHint(QSize(250,100));
    ui->evaluatelist->setItemWidget(li,ev);

    //填充到数据库
    db->insertvideoevaluation(ov->videoid,pi->pri->name,QTime::currentTime().toString(),"text",str,false,"",pi->pri->image);
}


void detailedvideoitem::on_pushButton_clicked()
{
    QString image=QFileDialog::getOpenFileName(this,"",QDir::currentPath());
    QPixmap pm(image);
    if(pm.isNull())
        return;
    evaluateitem* ev=new evaluateitem(ui->evaluatelist);
    ev->setFixedSize(QSize(160,160));
    ev->init(pi->pri->image,pi->pri->name,"image",image);
    QListWidgetItem* li=new QListWidgetItem(ui->evaluatelist);
    li->setSizeHint(QSize(160,160));
    ui->evaluatelist->setItemWidget(li,ev);
    //填充到数据库
    db->insertvideoevaluation(ov->videoid,pi->pri->name,QTime::currentTime().toString(),"image",image,false,"",pi->pri->image);
}


void detailedvideoitem::on_recommendvideolist_currentRowChanged(int currentRow)
{
    if(currentRow>=0&&currentRow<recommendov.size())
    {
        onevideoinfo* one=recommendov[currentRow];
        ui->recommendvideolist->clear();
        ui->evaluatelist->clear();
        ui->talklist->clear();
        emit changecurvideoid(one->videoid);
    }

}

